package com.agile.leetcode.hutool.crypto;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * 对称加密，使用同一个密钥
 *
 * @Author KD
 * @Date 2021/2/6 15:50
 */
@SuppressWarnings("all")
public class SymmetricCryptoDemo {
    /**
     * AES的实现
     */
    @Test
    public void test1() {
        String content = "czk";
        // 随机生成密钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        // 构建实例
        SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        // 加密
        byte[] encrypt = symmetricCrypto.encrypt(content.getBytes());
        System.out.println(new String(encrypt, StandardCharsets.UTF_8));
        // 解密
        byte[] decrypt = symmetricCrypto.decrypt(encrypt);
        System.out.println(new String(decrypt, StandardCharsets.UTF_8));
    }

    /**
     * DESede的实现
     */
    @Test
    public void test2(){
        String content = "czk";
        // 随机生成密钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DESede.getValue()).getEncoded();
        System.out.println(new String(key,StandardCharsets.UTF_8));
        // 构建实例
        SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.DESede, key);
        // 加密
        byte[] encrypt = symmetricCrypto.encrypt(content.getBytes());
        System.out.println(new String(encrypt, StandardCharsets.UTF_8));
        // 解密
        byte[] decrypt = symmetricCrypto.decrypt(encrypt);
        System.out.println(new String(decrypt, StandardCharsets.UTF_8));
    }
}
